package com.infore.airsupervise.ui.activity;

import android.Manifest;
import android.animation.ObjectAnimator;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v4.widget.DrawerLayout;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.MenuItem;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.animation.DecelerateInterpolator;
import android.view.animation.LinearInterpolator;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupMenu;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.beardedhen.androidbootstrap.AwesomeTextView;
import com.beardedhen.androidbootstrap.font.FontAwesome;
import com.github.lzyzsd.circleprogress.ArcProgress;
import com.infore.airsupervise.R;
import com.infore.airsupervise.adapter.FactorListAdapter;
import com.infore.airsupervise.app.Constants;
import com.infore.airsupervise.app.StatusConst;
import com.infore.airsupervise.bean.AQIRealDataE;
import com.infore.airsupervise.bean.AirStationE;
import com.infore.airsupervise.bean.UserE;
import com.infore.airsupervise.biz.AQIRealDataBiz;
import com.infore.airsupervise.biz.impl.AQIRealDataBizImpl;
import com.infore.airsupervise.http.OnServerResponseListener;
import com.infore.airsupervise.ui.fragment.AQIDrawerFragment;
import com.infore.airsupervise.ui.widget.MeasureListView;
import com.infore.airsupervise.utils.AirLevelUtil;
import com.infore.airsupervise.utils.JumpUtil;
import com.infore.airsupervise.utils.ToastUtil;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * 新AQI界面
 *
 * @作者: dingxinlin
 * @创建时间: 2017/4/25 9:59
 */
public class NewAQIActivity extends BaseActivity {

    @BindView(R.id.titlebar_left_menu)
    AwesomeTextView leftMenu;
    @BindView(R.id.titlebar_title)
    TextView title;
    @BindView(R.id.titlebar_right_menu)
    AwesomeTextView rightMenu;
    @BindView(R.id.layout_titleBar)
    LinearLayout titleBar;
    @BindView(R.id.layout_api)
    LinearLayout layoutApi;
    @BindView(R.id.aqi_progress)
    ArcProgress aqiProgress;
    @BindView(R.id.ic_windmill)
    ImageView icWindmill;
    @BindView(R.id.factor_list_view)
    MeasureListView factoListView;
    @BindView(R.id.ic_radar)
    ImageView icRadar;
    @BindView(R.id.layout_main)
    ScrollView layoutMain;
    @BindView(R.id.layout_waiting)
    FrameLayout layoutWaiting;
    @BindView(R.id.person_name)
    TextView personName;
    @BindView(R.id.person_phone)
    TextView personPhone;
    @BindView(R.id.person_address)
    TextView personAddress;
    @BindView(R.id.drawer_layout)
    DrawerLayout drawerLayout;

    private String mn;
    private AQIRealDataBiz aqiRealDataBiz;
    private FactorListAdapter adapter;
    private List<AQIRealDataE.FactorListBean> datas = new ArrayList<>();
    private AQIDrawerFragment drawerFragment  =null ;

    private String phone ;
    private UserE userE;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_new_aqi);
        ButterKnife.bind(this);

        // 状态栏透明
        tintManager.setStatusBarTintResource(Color.TRANSPARENT);

        mn = getIntent().getStringExtra(Constants.INTENT_STR_KEY);
        if (mn == null || mn.isEmpty()) {
            ToastUtil.showLong(ctx, "参数传递出错");
            return;
        }

        aqiRealDataBiz = new AQIRealDataBizImpl();

        initView();
        getData();
    }

    private void initView() {
        titleBar.setBackgroundColor(Color.TRANSPARENT);
        rightMenu.setFontAwesomeIcon(FontAwesome.FA_ELLIPSIS_V);

        // 雷达动画
        Animation radarAnim = AnimationUtils.loadAnimation(ctx, R.anim.anim_rotate_repeat);
        radarAnim.setInterpolator(new LinearInterpolator());
        icRadar.setAnimation(radarAnim);

        // 风车动画
        Animation windmillAnim = AnimationUtils.loadAnimation(ctx, R.anim.anim_rotate_repeat);
        windmillAnim.setDuration(3000);
        windmillAnim.setInterpolator(new LinearInterpolator());
        icWindmill.setAnimation(windmillAnim);

        // 因子列表
        adapter = new FactorListAdapter(ctx, datas);
        factoListView.setAdapter(adapter);
        //抽屉布局
        if(drawerFragment == null){
            drawerFragment = new AQIDrawerFragment();
        }
        drawerFragment.setStationMN(mn);
        getSupportFragmentManager().beginTransaction().replace(R.id.drawer_container, drawerFragment).commit();
    }

    /**
     * 获取数据
     */
    private void getData() {
        aqiRealDataBiz.sendAQIRealDataRequst(mn, new OnServerResponseListener<AQIRealDataE>() {
            @Override
            public void onSucceed(final AQIRealDataE result, String desc) {
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        showData(result);
                    }
                }, 1000);
            }

            @Override
            public void onFailed(int errorCode, String title, String desc) {
                ToastUtil.showLong(ctx, title);
            }
        });
    }

    /**
     * 展示数据（响应成功）
     */
    private void showData(AQIRealDataE dataE) {
        if (dataE == null || null == dataE.getFactorList()) {
            ToastUtil.showShort(ctx, "没有该站点的实时监控数据");
            icRadar.clearAnimation();
            icWindmill.clearAnimation();
            return;
        }

        // 等待视图隐藏
        icRadar.clearAnimation();
        layoutWaiting.setVisibility(View.GONE);
        layoutMain.setVisibility(View.VISIBLE);

        // 标题
        title.setText(dataE.getStationName());

        // 取数据，更新适配器
        double aqiValue = 0;
        for (AQIRealDataE.FactorListBean factor : dataE.getFactorList()) {
            if ("AQI".equals(factor.getName())) {
                aqiValue = factor.getValue();
            } else {
                // 因子数据 除AQI外
                datas.add(factor);
            }
        }

        if (aqiValue > 500) {
            aqiValue = 500;
        }
        if (aqiValue < 0) {
            aqiValue = 0;
        }
        adapter.notifyDataSetChanged();

        // 获取aqi等级
        AirStationE.AirLevel airLevel = AirLevelUtil.getAirLevelObj(StatusConst.AIR_TYPE_AQI, aqiValue);

        // 设置背景图
        if (airLevel.getLevel() < 3) {
            layoutApi.setBackgroundResource(R.drawable.bg_sunny);
        } else if (airLevel.getLevel() < 5) {
            layoutApi.setBackgroundResource(R.drawable.bg_mostly_cloudy);
        } else {
            layoutApi.setBackgroundResource(R.drawable.bg_cloudy);
        }


        int textColor = ContextCompat.getColor(ctx, airLevel.getColorRes());
        aqiProgress.setBottomText(airLevel.getLevelStr());
        aqiProgress.setTextColor(textColor);
        // 设置刻度值
        aqiProgress.setFinishedStrokeColor(textColor);
        ObjectAnimator oa = new ObjectAnimator().ofInt(aqiProgress, "progress", 0, (int) aqiValue);
        oa.setInterpolator(new DecelerateInterpolator());
        oa.setDuration(1000);
        oa.start();

        // 网格员信息
        phone = dataE.getPhone() ;
        personName.setText(TextUtils.isEmpty(dataE.getPsonName()) ? "暂无" : dataE.getPsonName());
        personPhone.setText(TextUtils.isEmpty(phone ) ? "暂无" : dataE.getPhone());
        personAddress.setText(TextUtils.isEmpty(dataE.getAddress()) ? "暂无" : dataE.getAddress());

    }

    @OnClick({R.id.titlebar_left_menu, R.id.titlebar_right_menu})
    void onTitleMenuClick(View view) {
        if (view.getId() == R.id.titlebar_left_menu) {
            finish();
        } else {
            //抽屉显示隐藏
            if (!drawerLayout.isDrawerOpen(Gravity.RIGHT)) {
                drawerLayout.openDrawer(Gravity.RIGHT);
            } else {
                drawerLayout.closeDrawers();
            }
        }
    }

    @OnClick({R.id.pson_call, R.id.pson_sms, R.id.pson_detail})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.pson_call:
                //电话
                if(phone == null){
                    ToastUtil.showShort(ctx, "号码为空");
                }else {
                    Intent itCall = new Intent(Intent.ACTION_CALL);
                    String tel = "tel:" + phone;
                    Uri uri = Uri.parse(tel);
                    itCall.setData(uri);
                    if (ActivityCompat.checkSelfPermission(this,
                            Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED) {
                        return;
                    }
                    startActivity(itCall);
                }
                break;
            case R.id.pson_sms:
                //短信
                if(phone == null){
                    ToastUtil.showShort(ctx, "号码为空");
                }else {
                    Uri uri = Uri.parse("smsto:"+phone);
                    Intent itSMS = new Intent(Intent.ACTION_SENDTO,uri);
                // itSMS.putExtra("address", phone );
                  //  itSMS.setType("vnd.android-dir/mms-sms");
                    startActivity(itSMS);
            }
                break;
            case R.id.pson_detail:
                ToastUtil.showShort(ctx, "暂无网格员信息");
                break;
        }
    }
}
